package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class ApBehaviorServcieImpl implements ApBehaviorServcie {

    @Autowired
    private StringRedisTemplate redisTemplate;



    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.效验参数
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.获取登录用户，判断是否登录
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if (apUser.getId() == null) {
            return ResponseResult.okResult(405, "游客身份禁止，需进行登录");
        }
        //假设用户的这些行为都是FALSE
        Boolean isfollow = false, iscollection = false, isunlike = false, islike = false;
        //3查询redis数据，用户的行为
        //3.1查看用户是否是关注
        String follow_hash_key = "USER_FOLLOW_" + apUser.getId();
        //获取判断
        Boolean followHasKey = redisTemplate.opsForHash().hasKey(follow_hash_key, dto.getAuthorId() + "");
        if (followHasKey) {
            isfollow = true;
        }
        //3.2查看用户是否是收藏
        String COLLECTION_hash_key = "USER_COLLECTION_" + dto.getArticleId();
        //获取判断
        Boolean collectionHasKey = redisTemplate.opsForHash().hasKey(COLLECTION_hash_key, apUser.getId() + "");
        if (collectionHasKey) {
            iscollection = true;
        }
        //3.3查看用户是否是不喜欢
        String unlike_hash_key = "USER_UNLIKES" + dto.getArticleId();
        //3.1判断是已经不喜欢：查询关注缓存中的小key是否包含点赞人id
        Boolean unlikeHasKey = redisTemplate.opsForHash().hasKey(unlike_hash_key, apUser.getId()+"");
        if (unlikeHasKey) {
            isunlike = true;
        }
        //3.4查看用户是否是喜欢
        String like_hash_key = "USER_LIKES_" + dto.getArticleId();
        //3.3判断是已经点赞：查询关注缓存中的小key是否包含点赞人id
        Boolean likeHasKey = redisTemplate.opsForHash().hasKey(like_hash_key, apUser.getId() + "");
        if (likeHasKey) {
            islike = true;
        }
        //7.返回数据
        Map map=new HashMap();
        map.put("isfollow",isfollow);
        map.put("iscollection",iscollection);
        map.put("isunlike",isunlike);
        map.put("islike",islike);
        return ResponseResult.okResult(map);
    }
}
